package lumis.doui.processaction;

import lumis.doui.source.Source;
import lumis.portal.PortalException;
import lumis.portal.manager.ManagerFactory;
import lumis.portal.serviceinstance.ServiceInstanceConfig;
import lumis.portal.serviceinstance.ServiceInstanceDependencyConfig;
import lumis.portal.serviceinterfaceinstance.ServiceInterfaceInstanceConfig;
import lumis.util.PortalUtil;
import lumis.util.XmlUtil;

/**
 * Process Action handler that sets the service instance repository dependency.
 *
 * @version $Revision: 9601 $ $Date: 2008-07-18 15:38:17 -0300 (Fri, 18 Jul 2008) $
 * @since 4.2.0
 */
public class SelectRepositoryProcessActionHandler extends ProcessActionHandler<Source<?>>
{
	public void processAction() throws PortalException
	{
		String dependencyType = XmlUtil.readNodeString("dependencyType", this.processActionNode);
		
		if(dependencyType == null)
			throw new PortalException("dependencyType node not specified for SelectRepositoryProcessActionHandler");
		
		String serviceInterfaceInstanceId = douiContext.getRequest().getCallerServiceInterfaceInstanceId();
		ServiceInterfaceInstanceConfig callerInterfaceInstanceConfig = ManagerFactory.getServiceInterfaceInstanceManager().get(sessionConfig, serviceInterfaceInstanceId, transaction);

		String serviceInstanceId = douiContext.getRequest().getParameter("serviceInstanceId");
		if (serviceInstanceId != null)
		{
			String curServiceId = douiContext.getRequest().getServiceConfig().getId();
			
			// check if the service instance is a service of the pop interface
			ServiceInstanceConfig serviceInstanceConfig = ManagerFactory.getServiceInstanceManager().get(serviceInstanceId, transaction);
			if (!curServiceId.equals(serviceInstanceConfig.getServiceId()))
			{
				throw new PortalException("Invalid service instance service. Expected :"+ curServiceId);
			}
		}
		
		ServiceInstanceDependencyConfig dependencyConfig = new ServiceInstanceDependencyConfig();
		dependencyConfig.setId(PortalUtil.generateNewGuid());
		dependencyConfig.setServiceInstanceId(serviceInstanceId);
		dependencyConfig.setDependentServiceInstanceId(callerInterfaceInstanceConfig.getServiceInstanceId());
		dependencyConfig.setDependencyType(dependencyType);			
		ManagerFactory.getServiceInstanceManager().setServiceInstanceDependency(dependencyConfig, transaction);
		
		addDefaultResponse();
	}
}
